package apptoko.com;

import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import apptoko.com.adapter.NotificationHelper;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.db.DatabaseHelper;
import apptoko.com.download.DownloadManager;
import apptoko.com.download.DownloadService;
import apptoko.com.download.DownloadManager.Request;
import apptoko.com.event.Event;
import apptoko.com.event.Event.BuyAttachedSuccessEvent;
import apptoko.com.event.Event.GetAttachedDownloadLinkSuccess;
import apptoko.com.event.Event.GetDownloadLinkSuccess;
import apptoko.com.event.Event.GiftboxNotExists;
import apptoko.com.event.Event.ReportGiftboxFail;
import apptoko.com.event.Event.ReportGiftboxSuccess;
import apptoko.com.event.Event.ReportInstallFail;
import apptoko.com.model.DownloadLink;
import apptoko.com.model.GiftSetting;
import apptoko.com.model.Giftbox;
import apptoko.com.util.Constants;
import apptoko.com.util.StorageUtils;
import apptoko.com.util.Utils;
import apptoko.com.util.WakeLocker;

import com.appota.asdk.commons.AccessTokenUtil;
import apptoko.com.R;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gcm.GCMRegistrar;

import de.greenrobot.event.EventBus;

public class NotificationService extends Service {
	
	private BackgroundTasks bgTask;
	private InstallReceiver installReceiver;
	private NotificationHelper notification;
	public static final String ACTION_DOWNLOADED = "appstorevn.intent.downloaded";
	public static final String KEY_TYPE = "downloaded_type";
	public static final String KEY_PATH = "downloaded_path";
	public static final String OTA_INSTALL = "OTAINSTALL";
	private AsyncTask<Void, Void, Void> mRegisterTask;
	private DownloadManager downloadManager;
	private String accessToken;
	private boolean isRooted;
	private String slug;
	private String versionId;
	private static final int REQUEST_CODE_LAUNCH = 403;
	private static final int REQUEST_CODE_SHARE = 405;
	private DatabaseHelper db;
	private GiftSetting gift;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		db = new DatabaseHelper(this);
		accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
		if (null == accessToken || accessToken.equals(null)) {
			accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		}
		EventBus.getDefault().register(this);
		downloadManager = new DownloadManager(getContentResolver(), getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
		boolean isRooted1 = ((AppStoreVnApplication) getApplication()).isRooted();
		isRooted = Utils.isRootedStatic(this, isRooted1);
		notification = new NotificationHelper(this);
		bgTask = new BackgroundTasks(this);
        EasyTracker.getInstance().setContext(this);
        installReceiver = new InstallReceiver();
        IntentFilter packageFilter = new IntentFilter();
		packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
		packageFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
		packageFilter.addDataScheme("package");
		registerReceiver(installReceiver, packageFilter);
		registerGCM();
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(this, DownloadService.class);
		startService(intent);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		unregisterReceiver(installReceiver);
		if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        try {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }
	}
	
	private void registerGCM(){
//        if (ContentNetworkInterface.SERVER_URL == null || ContentNetworkInterface.SENDER_ID == null || ContentNetworkInterface.SERVER_URL.length() == 0 || ContentNetworkInterface.SENDER_ID.length() == 0) {
//        	Toast.makeText(this, "miss configuration", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        GCMRegistrar.checkDevice(this);
//        GCMRegistrar.checkManifest(this);
        registerReceiver(mHandleMessageReceiver, new IntentFilter(GCMIntentService.DISPLAY_MESSAGE_ACTION));
//        final String regId = GCMRegistrar.getRegistrationId(this);
//        System.err.println(regId);
//        if (regId.equals("")) {
//            GCMRegistrar.register(this, ContentNetworkInterface.SENDER_ID);
//        } else {
//            if (GCMRegistrar.isRegisteredOnServer(this)) {
//                // Skips registration.
//            } else {
//                final Context context = this;
//                mRegisterTask = new AsyncTask<Void, Void, Void>() {
//                    @Override
//                    protected Void doInBackground(Void... params) {
//                        try {
//                        	String accessToken = ((AppStoreVnApplication)getApplication()).getAccessToken();
//                        	if(null == accessToken || accessToken.equals(null)){
//                    			SharedPreferences pref = getSharedPreferences(Constants.PREF_ACCESSTOKEN, Context.MODE_PRIVATE);
//                    			accessToken = pref.getString(Constants.ACCESS_TOKEN, "");
//                    		}
//                            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
//                            String allowPush = pref.getString(SettingsActivity.KEY_ALLOW_PUSH, "1");
//                            boolean isRooted1 = ((AppStoreVnApplication) getApplication()).isRooted();
//                            boolean isRooted = Utils.isRootedStatic(context, isRooted1);
//                            String root;
//                            if(isRooted){
//                            	root = "1";
//                            } else {
//                            	root = "0";
//                            }
//                            bgTask.registerGCM(accessToken, regId, allowPush, root, 0);
//						} catch (NameNotFoundException e) {
//							e.printStackTrace();
//						}
//                        return null;
//                    }
// 
//                    @Override
//                    protected void onPostExecute(Void result) {
//                        mRegisterTask = null;
//                    }
// 
//                };
//                mRegisterTask.execute(null, null, null);
//            }
//        }
	}
	
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	Bundle data = intent.getExtras();
            WakeLocker.acquire(getApplicationContext());
            if(data.getString("title").equals(OTA_INSTALL)){
            	//OTA install
            	String OTAContent = data.getString("content_id");
            	StringTokenizer tokenizer = new StringTokenizer(OTAContent, "/");
            	while(tokenizer.hasMoreElements()){
            		slug = tokenizer.nextElement().toString();
            		@SuppressWarnings("unused")
					String ota = tokenizer.nextElement().toString();
            		versionId = tokenizer.nextElement().toString();
            	}
            	accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
        		if (null == accessToken || accessToken.equals(null)) {
        			accessToken = AccessTokenUtil.getInstance().init(NotificationService.this).getSavedAccessToken();
        		}
            	bgTask.getDownloadLink("service", accessToken, slug, Long.valueOf(versionId), isRooted, "push");
            } else {
            	SharedPreferences sharedPref = getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
            	String allowPush = sharedPref.getString(SettingsActivity.KEY_ALLOW_PUSH, "true");
            	if(allowPush.equals("true")){
            		notification.createPushNotification(data);
            	}
            }
            WakeLocker.release();
        }
    };

	private class InstallReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED) || intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)){
				String packageName = intent.getDataString().split(":")[1];
				PackageManager pm = getPackageManager();
				PackageInfo info;
				try {
					info = pm.getPackageInfo(packageName, 0);
					String title = info.applicationInfo.loadLabel(pm).toString();
					Drawable icon = info.applicationInfo.loadIcon(pm);
					Bitmap largeIcon = ((BitmapDrawable) icon).getBitmap();
					int notificationId = title.length(); 
					EasyTracker.getTracker().sendEvent(Constants.INSTALL_EVENT, Constants.INSTALL_SUCCESS, title, Long.valueOf(10));
					Intent notifyIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
					if(null != notifyIntent){
						notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					    PendingIntent pending = PendingIntent.getActivity(context, REQUEST_CODE_LAUNCH, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
						notification.complete(notificationId, largeIcon, title, context.getResources().getString(R.string.install_success), context.getResources().getString(R.string.install_success), pending);
					} else {
						Intent completeIntent = new Intent();
						completeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					    PendingIntent pending = PendingIntent.getActivity(context, REQUEST_CODE_LAUNCH, completeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
						notification.complete(notificationId, largeIcon, title, context.getResources().getString(R.string.install_success), context.getResources().getString(R.string.install_success), pending);
					}
					gift = db.getGift(packageName);
					if(gift != null){
						accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
						if (null == accessToken || accessToken.equals(null)) {
							accessToken = AccessTokenUtil.getInstance().init(NotificationService.this).getSavedAccessToken();
						}
						bgTask.reportInstall(accessToken, gift.getSlug(), 0, "success");
						if(gift.getDays() == 0){
							bgTask.reportGiftbox(accessToken, gift.getSlug(), "check", packageName);
						}
					}
				} catch (NameNotFoundException e) {
					e.printStackTrace();
				}
			} else if(intent.getAction().equalsIgnoreCase(Intent.ACTION_PACKAGE_REMOVED)){
				String packageName = intent.getDataString().split(":")[1];
				GiftSetting gift = db.getGift(packageName);
				if(gift != null){
					db.deleteGift(packageName);
					accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
					if (null == accessToken || accessToken.equals(null)) {
						accessToken = AccessTokenUtil.getInstance().init(context).getSavedAccessToken();
					}
					bgTask.reportGiftbox(accessToken, gift.getSlug(), "cancel", packageName);
				}
			}
		}
	}
	
	public void onEventMainThread(Event.DownloadSuccessEvent e){
		EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.DOWNLOAD_COMPLETE_ACTION, Constants.DOWNLOAD_COMPLETED + e.getName() + " in " + e.getStore() + " store", Long.valueOf(1));
	}
	
	public void onEventMainThread(ReportInstallFail e){
		accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
		if (null == accessToken || accessToken.equals(null)) {
			accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		}
		bgTask.reportInstall(accessToken, gift.getSlug(), 0, "success");
	}
	
	public void onEventMainThread(BuyAttachedSuccessEvent e){
		accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
		if (null == accessToken || accessToken.equals(null)) {
			accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		}
		bgTask.getAttachedDownloadLink("attach", accessToken, e.getSlug(), 0, isRooted, "direct");
	}
	
	public void onEventMainThread(GetAttachedDownloadLinkSuccess event){
		if(event.getTopType().equalsIgnoreCase("attach")){
			DownloadLink download = event.getDl();
			List<String> extraUrls = download.getExtraDownloads();
			if(extraUrls.size() > 0){
				for(String extraUrl : extraUrls){
					Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
					DownloadManager.Request request = new Request(srcUri);
					if(extraUrl.endsWith("obb")){
						String obbDir = StorageUtils.OBB_ROOT + Utils.getFileName(extraUrl) + "/";
						File obb = new File(obbDir);
						if(!obb.exists()){
							obb.mkdirs();
						}
						request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
					} else {
						request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
					}
					request.setTitle(String.format(getResources().getString(R.string.additional_file), Utils.getFileName(extraUrl)));
					request.setDescription(Utils.getFileName(extraUrl));
					downloadManager.enqueue(request);
				}
			}
			String url = download.getDownload();
			Uri srcUri = Uri.parse(url.replace(" ", "%20"));
			DownloadManager.Request request = new Request(srcUri);
			request.setTitle(Utils.getFileName(url));
			request.setDescription(url);
			setDownloadData(request, url);
			downloadManager.enqueue(request);
		}
	}
	
	public void onEventMainThread(ReportGiftboxSuccess e){
		accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
		if (null == accessToken || accessToken.equals(null)) {
			accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		}
		if(e.getType().equalsIgnoreCase("check")){
			gift = db.getGift(e.getPackageName());
			Giftbox giftbox = e.getGift();
			if(giftbox.getUsed() == 0){
				NotificationHelper notification = new NotificationHelper(getApplicationContext());
				Intent share = new Intent(this, PostFacebookActivity.class);
				String type = giftbox.getType();
				if(type.equalsIgnoreCase("yellow_tym")){
					type = getResources().getString(R.string.yellow_tym);
				} else {
					type = getResources().getString(R.string.purple_tym);
				}
				share.putExtra(Constants.SHARE_MESSAGE, String.format(getResources().getString(R.string.gift_share_message), gift.getAppName(), giftbox.getValue(), type));
				share.putExtra(Constants.SLUG, gift.getSlug());
				share.putExtra(Constants.SHARE_PICTURE, gift.getPicture());
				share.putExtra(Constants.SHARE_NAME, gift.getAppName());
				share.putExtra(Constants.SHARE_LINK, Constants.APPTOKO_PC + gift.getName());
				share.putExtra(Constants.PACKAGE_NAME, gift.getName());
				PendingIntent pending = PendingIntent.getActivity(this, REQUEST_CODE_SHARE, share, PendingIntent.FLAG_ONE_SHOT);
				notification.createGiftNotification(String.format(getResources().getString(R.string.share_to_get_gift), giftbox.getValue() + " " + type), getResources().getString(R.string.message_congratulations), pending, getResources().getString(R.string.click_to_share), 1);
			}
		} else {
			if(e.getPackageName() != null){
				db.deleteGift(e.getPackageName());
			}
		}
	}
	
	public void onEventMainThread(GiftboxNotExists e){
		System.err.println(e.getMessage());
	}
	
	public void onEventMainThread(ReportGiftboxFail e){
		accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
		if (null == accessToken || accessToken.equals(null)) {
			accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		}
		bgTask.reportGiftbox(accessToken, gift.getSlug(), e.getType(), gift.getName());
	}
	
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(event.getTopType().equalsIgnoreCase("service")){
			DownloadLink download = event.getDl();
			List<String> extraUrls = download.getExtraDownloads();
			if(extraUrls.size() > 0){
				for(String extraUrl : extraUrls){
					Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
					DownloadManager.Request request = new Request(srcUri);
					if(extraUrl.endsWith("obb")){
						String obbDir = StorageUtils.OBB_ROOT + Utils.getFileName(extraUrl) + "/";
						File obb = new File(obbDir);
						if(!obb.exists()){
							obb.mkdirs();
						}
						request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
					} else {
						request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
					}
					request.setTitle(String.format(getResources().getString(R.string.additional_file), Utils.getFileName(extraUrl)));
					request.setDescription(Utils.getFileName(extraUrl));
					downloadManager.enqueue(request);
				}
			}
			String url = download.getDownload();
			Uri srcUri = Uri.parse(url.replace(" ", "%20"));
			DownloadManager.Request request = new Request(srcUri);
			request.setTitle(Utils.getFileName(url));
			request.setDescription(url);
			setDownloadData(request, url);
			downloadManager.enqueue(request);
		}
	}
	
	private void setDownloadData(Request request, String url){
		if(url.endsWith("apk")){
			request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
		} else if(url.endsWith("epub")){
			request.setMimeType(StorageUtils.EBOOK_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.EBOOK_ROOT + Utils.getFileName(url))));
		} else if(url.endsWith("zip")){
			request.setMimeType(StorageUtils.COMIC_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.COMIC_ROOT + Utils.getFileName(url))));
		} else if(url.endsWith("mp4")){
			request.setMimeType(StorageUtils.MOVIES_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.MOVIES_ROOT + Utils.getFileName(url))));
		} else {
			request.setMimeType(StorageUtils.DATA_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.DATA_ROOT + Utils.getFileName(url))));
		}
	}

	public void onEventMainThread(Event.ConfirmGiftBoxSuccess e){
		String slug = e.getSlug();
		String content = slug + ":1";
		accessToken = ((AppStoreVnApplication) getApplication()).getAccessToken();
		if (null == accessToken || accessToken.equals(null)) {
			accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		}
		bgTask.createUserSetting(accessToken, "gift" + slug.replace("-", "").trim(), content, 1);
		GiftSetting gs = new GiftSetting();
		gs.setSlug(slug);
		gs.setReceived(1);
		db.addGiftSync(gs);
	}
	
	public void onEventMainThread(Event.DeleteFileEvent e){
		if(e.isDeleted()){
			Toast.makeText(getApplicationContext(), R.string.deleted, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(getApplicationContext(), R.string.delete_error, Toast.LENGTH_SHORT).show();
		}
	}
}
